import {Inject, Injectable} from '@angular/core';
import {Headers, Http, RequestOptions, Response, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
import {Router} from '@angular/router';
import {NzNotificationService} from 'ng-zorro-antd';
import {NzNotificationData} from 'ng-zorro-antd/src/notification/nz-notification.definitions';
import {DA_SERVICE_TOKEN, ITokenService} from '@delon/auth';
import {PlatformLocation} from '@angular/common';

@Injectable()
export class UtilityService {
    constructor(private http: Http,
                private router: Router,
                private nznot: NzNotificationService,
                @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
                location: PlatformLocation
                ) {
            console.log(location)
    }

    token: any; // 请求头token
    // 跳转路由 原理 通过catch 拦截异常，然后在抛出一个新的错误
    public httpErrorFun(err: any) {  /* new */
        let data: any = err.json();  // 需要处理的值 /* new */
        if(location.hash !== '#/passport/login') { // 登录页的不判断，除了登录页之外的都要判断
            if (data.code === '401') {
                // this.nznot.create('error', '认证失败' , '请重新登陆');
                this.router.navigateByUrl('/passport/login');
            }
        }
        return Observable.throw(data); /* new */
    }

    /**
     * @param {string} url地址
     * @param {any} [options]可选提交的参数
     * @param {any} [header]可选设置的头信息
     * @memberof ServiceBaseService
     * @title: 封装一个get请求的基础类
     */
    getData(url: string, options?: any, myheaders?: any): Observable<any> {
        myheaders = {Authorization: 'Bearer ' + this.tokenService.get().token}
        // 配置请求头
        const myHeaders: Headers = new Headers();
        // tslint:disable-next-line:forin
        for (const key in myheaders) {
            myHeaders.append(key, myheaders[key]);
        }
        url += (url.indexOf('?') < 0 ? '?' : '&') + this.param(options);
        return this.http.get(url, { headers: myHeaders })
            .catch(res => this.httpErrorFun(res))
            .map(res => res.json());
    }


    /**
     * @param url地址
     * @param options提交的数据
     * @param myheaders可选参数设置头
     * @title:封装一个post请求数据的
     */
    postData(url: string, options: any, myheaders?: any): Observable<any> {
        if (url.slice( url.indexOf('?') - 5, url.indexOf('?')) !== 'token') { // 登陆的时候 不能用通用的
            myheaders = {Authorization: 'Bearer ' + this.tokenService.get().token}
        }
        const myHeaders: Headers = new Headers();
        myHeaders.append('Content-Type', 'application/json');
        for (const key in myheaders) {
            myHeaders.append(key, myheaders[key]);
        }
        return this.http.post(url, options, { headers: myHeaders })
            .catch(res => this.httpErrorFun(res))
            .map(res => res.json());

    }


    // put 修改测试封装
    putData(url: string, options?: any, myheaders?: any): Observable<any> {
        myheaders = {Authorization: 'Bearer ' + this.tokenService.get().token}
        const myHeaders: Headers = new Headers();
        myHeaders.append('Content-Type', 'application/json');
        for (const key in myheaders) {
            myHeaders.append(key, myheaders[key]);
        }
        return this.http.put(url, options, { headers: myHeaders })
            .catch(res => this.httpErrorFun(res))
            .map(res => res.json());;
    }

    // 删除封装
    deleatData(url: string, myheaders?: any): Observable<any> {
        if (url.indexOf('uaa/exit') < 0) { // 代表找不到，即代表不是登出,那么就加上公共请求头
            myheaders = {Authorization: 'Bearer ' + this.tokenService.get().token}
        }
        const myHeaders: Headers = new Headers();
        myHeaders.append('Content-Type', 'application/json');
        for (const key in myheaders) {
            myHeaders.append(key, myheaders[key]);
        }

        return  this.http.delete(url, { headers: myHeaders })
            .catch(res => this.httpErrorFun(res))
            .map(res => res.json());;

    }


    /**
     * @param {any} data
     * @returns
     * @memberof ServiceBaseService
     * @title:封装一个序列化get请求的参数的方法
     */
    param(data): string {
        let url = '';
        for (const k in data) {
            const value = data[k] !== undefined ? data[k] : '';
            url += `&${k}=${encodeURIComponent(value)}`;
        }
        return url ? url.substring(1) : '';
    }


    getBillTypes() {

    }


}
